<template>
    <el-form ref="noticeRef" :model="noticeForm" label-width="0">
        <el-row :gutter="15">
            <el-col :span="4">
                <el-form-item prop="title">
                    <el-input v-model.trim="noticeForm.title" maxlength="20" placeholder="请输入标题" show-word-limit/>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item prop="context">
                    <el-input v-model.trim="noticeForm.context" maxlength="20" placeholder="请输入公告内容"
                              show-word-limit/>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item prop="time">
                    <el-date-picker
                            v-model.trim="noticeForm.time"
                            :clearable="false"
                            end-placeholder="请输入结束时间"
                            range-separator="到"
                            start-placeholder="请输入开始时间"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6" class="btn">
                <el-button :icon="Search" plain type="primary" @click="submitForm">搜索</el-button>
                <el-button :icon="Refresh" plain @click="resetForm()">重置</el-button>
                <el-button :icon="Plus" plain type="success" @click="addNotice">添加公告</el-button>
            </el-col>
        </el-row>
    </el-form>
    <AddNotice ref="son" @update="resetForm()"/>
</template>

<script lang='ts' setup>
import { onUnmounted, ref } from 'vue'
import { Notice } from '@/ts/type'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import { FormInstance } from 'element-plus'
import { EventBus } from '@/utils/mitt'
import { isEmpty } from '@/utils/commonUtils'
import { Message } from '@/plugins/element'
import { noticeInit } from '@/config/formConfig'
import AddNotice from '@/components/notice/addNotice.vue'

const noticeForm = ref<Notice>({ ...noticeInit })
const noticeRef = ref<FormInstance>()
const son = ref()

// 模糊查询表单提交
const submitForm = () => {
  const { title, context, time } = noticeForm.value
  if (isEmpty(title) && isEmpty(context) && isEmpty(time as string[])) {
    return Message.warning('请至少输入一项内容')
  }
  EventBus.emit('noticeSearchForm', noticeForm.value)
}

// 表单内容重置
const resetForm = () => {
  EventBus.emit('noticeOpen', false)
  noticeForm.value = { ...noticeInit }
}

// 添加公告
const addNotice = () => {
  son.value.noticeDialog()
}

// 销毁当前页面的事件总线
onUnmounted(() => {
  EventBus.off('noticeOpen')
  EventBus.off('noticeSearchForm')
})

</script>

<style lang='scss' scoped>
.el-col > .el-form-item {
  margin-bottom: 0;
}

.btn {
  display: flex;
  justify-content: space-around;
}
</style>